<?php

declare(strict_types=1);

namespace App\Controller;


use App\Helps\Data;
use App\Model\Menu;
use App\Model\Role;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;


/**
 * Class RoleController
 * @package App\Controller
 */
class RoleController extends AbstractController
{

    public function index(RequestInterface $request, ResponseInterface $response)
    {
        $pageSize = (int)$request->input('pageSize', 10);
        $inputs = $request->inputs(['keyword']);

        $builder = Role::query();
        if ($inputs['keyword']) {
            $builder->where('title', 'like', sprintf('%%%s%%', $inputs['keyword']));
        }
        $records = $builder->orderByDesc('id')->paginate($pageSize, ['*'], 'current');
        $items = $records->items();

        return $response->json([
            'pagination' => [
                'total' => $records->total(),
                'pageSize' => $pageSize,
                'current' => $records->currentPage()

            ],
            'list' => $items
        ]);
    }

    public function allMenus(ResponseInterface $response)
    {
        $records = Menu::all()->toArray();
        $treesList = Data::listToTree($records, 'id', 'pid', 'children');
        return $response->json(['data' => $treesList]);
    }

    public function roleMenus(int $roleId, ResponseInterface $response)
    {
        $role = Role::query()->where(['id' => $roleId])->first();
        if ($role) {
            $roleMenus = $role->menus->toArray();
        }
        return $response->json(['data' => $roleMenus ?? [], 'roleInfo' => $role]);
    }

    public function saveMenus(int $roleId, RequestInterface $request, ResponseInterface $response)
    {
        $newMenuIds = $request->input('menus');
        $role = Role::query()->where(['id' => $roleId])->first();


        if ($role) {
            $menuIds = Db::table('role_menu')->where(['role_id' => $role->id])
                ->get()->pluck('menu_id')->toArray();

            $addMenuIds = array_diff($newMenuIds, $menuIds);
            if ($addMenuIds) {
                array_walk($addMenuIds, function (&$item) use (&$roleId) {
                    $item = [
                        'menu_id' => $item,
                        'role_id' => $roleId
                     ];
                });
                Db::table('role_menu')->insert($addMenuIds);
            }

            $delMenus = array_diff($menuIds, $newMenuIds);
            if ($delMenus) {
                Db::table('role_menu')->where('role_id', $roleId)->whereIn('menu_id', $delMenus)->delete();
            }
        }
        return $response->json(['message' => '操作成功', 'status' => STATUS_SUCCESS]);
    }

    public function save(int $id, RequestInterface $request, ResponseInterface $response)
    {
        $inputs = $request->inputs(['title']);
        Role::query()->updateOrCreate(['id' => $id], $inputs);
        return $response->json(['message' => '操作成功', 'status' => STATUS_SUCCESS]);
    }

    public function detail(int $id, ResponseInterface $response)
    {
        if ($id) {
            $record = Role::query()->find($id);
        }
        return $response->json(['data' => !empty($record) ? $record->toArray() : []]);
    }

    public function batchDelete(RequestInterface $request, ResponseInterface $response)
    {
        $ids = $request->input('ids');
        Role::query()->whereIn('id', $ids)->delete();
        return $response->json(['message' => '操作成功', 'status' => STATUS_SUCCESS]);
    }
}
